import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Card, Button, Badge, Divider, Modal, Popconfirm, Icon ,Table} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './TableList.less';
import TestRecordForm from './TestRecordForm';
import RemarksForm from './RemarksForm';
import _ from 'lodash';



@connect(({ testrecord, project, user, loading }) => ({
  testrecord,
  list: testrecord.list,
  pagination: testrecord.pagination,
  selectedRows: testrecord.selectedRows,
  testStatusList: testrecord.testStatusList,
  formModalVisible: testrecord.formModalVisible,
  activeRecord: testrecord.activeRecord,
  projectList: project.list,
  currentUserOwnedProjectList: project.currentUserOwnedProjectList,
  currentUser: user.currentUser,
  loading: loading.effects['testrecord/list']
}))
export default class TableList extends PureComponent {

  state = {
    sign : null,
    visible : false,
    record:null,
    filteredInfo: null,
    sortedInfo: null,
  }
  componentDidMount() {
    this.props.dispatch({
      type: 'testrecord/list',
      payload: { pagination: { current: 1, pageSize: 10 } }
    })

    this.props.dispatch({
      type: 'project/list'
    });
    this.props.dispatch({
      type: 'user/fetchCurrent'
    })
    this.props.dispatch({
      type: 'project/queryCurrentUserOwnedProjects',
    }) 
  }

  handleStandardTableChange = (pagination, filters, sorter) => {
    this.setState({
      filteredInfo: filters,
      sortedInfo: sorter,
    });
    // this.props.dispatch({
    //   type: 'testrecord/list',
    //   payload: { pagination, filtersArg, sorter }
    // });
  };

  handleSelectedRows = rows => {
    this.props.dispatch({
      type: 'testrecord/setSelectedRows',
      payload: rows
    })
  };

  checkUserInProject = params => {
    let { currentUserOwnedProjectList } = this.props;
    let isUserInProject = currentUserOwnedProjectList.some(cp => {
      return cp.id == params.projectId;
    })
    if (!isUserInProject) {
      return Modal.info({
        title: '权限管理',
        content: `您不属于项目"${params.projectName}"的成员，无法提测，请找相关负责人添加您到项目组吧！`,
        destroyOnClose: true
      });
    }
  }

  checkUserInAnyProject = () => {
    let { currentUserOwnedProjectList } = this.props;
    if (_.isEmpty(currentUserOwnedProjectList)) {
      return Modal.info({
        title: '权限管理',
        content: `您不属于任何项目的成员，无法提测，请找相关负责人添加您到项目组吧！`,
        destroyOnClose: true
      });
    }
  }

  checkUserRole = (roleId, errMsg) => {
    let { currentUser } = this.props;
    if (currentUser && currentUser.roleId !== roleId) {
      return Modal.info({
        title: '权限管理',
        content: errMsg,
        destroyOnClose: true
      });
    }
  }

  handleGoToTest (params) {
    let modal1 = this.checkUserRole(2, '只有开发才可提测哦！');
    if (_.isUndefined(modal1)) {
      if ( params) {
        let modal2 = this.checkUserInProject(params);
        if (_.isUndefined(modal2)) {
          this.props.dispatch({
            type: 'testrecord/gotoTestRecordFormPage',
            payload: params
          })
        } else {
          return modal2;
        }
      } else{
        let modal3 = this.checkUserInAnyProject();
        if (_.isUndefined(modal3)) {
          this.props.dispatch({
            type: 'testrecord/gotoTestRecordFormPage',
            payload: params
          })
        } else {
          return modal3
        }
      }
    } else {
      return modal1;
    }
  };

  mapTestStatusCell = value => {

    let statusMap = ['warning', 'processing', 'error', 'processing', 'error', 'success', 'default'];
    let text = this.props.testStatusList.filter((ts) => {
      return parseInt(ts.value) === value;
    })[0].text;
    return <Badge status={statusMap[value]} text={text} />;
  }

  pmCheck (record)  {

    let pmCheckPass = testrecordId => {
      this.props.dispatch({
        type: 'testrecord/pmCheckPass',
        payload: testrecordId
      })
    }
  
    let pmCheckFail = testrecordId => {
      this.props.dispatch({
        type: 'testrecord/pmCheckFail',
        payload: testrecordId
      })
    }
    let modal1 = this.checkUserRole(1, '非产品人员，无权操作！');
    if (_.isUndefined(modal1)) {
      let modal2 = this.checkUserInProject(record);
      if (_.isUndefined(modal2)) {
        return Modal.confirm({
          title:"产品审核",
          maskClosable:true,
          destroyOnClose:true,
          onOk:() => pmCheckPass(record.activeTestRecordId),
          onCancel:() => pmCheckFail(record.activeTestRecordId),
          okText:"通过",
          cancelText:"不通过",
          content:(<div>
            <p>项目版本：{`${record.projectName}-${record.versionName}`}</p>
            <p>1. 请查看提测版本的功能是否完整</p>
            <p>2. 请查看提测版本的文案是否正确</p>
          </div>)
        })

      } else {
        return modal2;
      }
    } else {
      return modal1;
    }
  }

  pmCheckPass (record)  {
    let data = {
      id:record.activeTestRecordId,
      name:record.projectName,
      version:record.versionName
    }
    let confirm = data => {
      this.props.dispatch({
        type: 'testrecord/pmCheckPass',
        payload: data
      })
    }
  
    let modal1 = this.checkUserRole(1, '非产品人员，无权操作！');
    if (_.isUndefined(modal1)) {
      let modal2 = this.checkUserInProject(record);
      if (_.isUndefined(modal2)) {
        return Modal.confirm({
          title:"产品审核通过",
          maskClosable:true,
          destroyOnClose:true,
          onOk:() => confirm(data),
          okText:"确认",
          cancelText:"取消",
          content:(<div>
            <p>项目版本：{`${record.projectName}-${record.versionName}`}</p>
            <p>1. 请查看提测版本的功能是否完整</p>
            <p>2. 请查看提测版本的文案是否正确</p>
          </div>)
        })

      } else {
        return modal2;
      }
    } else {
      return modal1;
    }
  }

  pmCheckFail (record)  {

    let confirm = testrecordId => {
      this.props.dispatch({
        type: 'testrecord/pmCheckFail',
        payload: testrecordId
      })
    }
    let modal1 = this.checkUserRole(1, '非产品人员，无权操作！');
    if (_.isUndefined(modal1)) {
      let modal2 = this.checkUserInProject(record);
      if (_.isUndefined(modal2)) {
        this.setState({
          visible:true,
          sign:1,
          record:record,
        })

      } else {
        return modal2;
      }
    } else {
      return modal1;
    }
  }

  testerCheckPass (record ) {
    let data = {
      id:record.activeTestRecordId,
      name:record.projectName,
      version:record.versionName
    }
    let confirm = data => {
      this.props.dispatch({
        type: 'testrecord/testCheckPass',
        payload: data
      })
    }
  
    let modal1 = this.checkUserRole(3, '非测试人员，无权操作！');
    if (_.isUndefined(modal1)) {
      let modal2 = this.checkUserInProject(record);
      if (_.isUndefined(modal2)) {
        return Modal.confirm({
          title:"测试审核通过",
          maskClosable:true,
          destroyOnClose:true,
          onOk:() => confirm(data),
          okText:"确认",
          cancelText:"取消",
          content:(<div>
            <p>项目版本：{`${record.projectName}-${record.versionName}`}</p>
            <p>1. 请查看开发是否自测通过</p>
            <p>2. 快速验证基本功能（15-30min内完成，若验证未通过，务必打回）</p>
          </div>)
        })
      } else {
        return modal2;
      }
    } else {
      return modal1;
    }
  }

  testerCheckFail (record ) {
     
    let confirm = testrecordId => {
      this.props.dispatch({
        type: 'testrecord/testCheckFail',
        payload: testrecordId
      })
    }
    let modal1 = this.checkUserRole(3, '非测试人员，无权操作！');
    if (_.isUndefined(modal1)) {
      let modal2 = this.checkUserInProject(record);
      if (_.isUndefined(modal2)) {
        this.setState({
          visible:true,
          sign:2,
          record:record,
        })
      } else {
        return modal2;
      }
    } else {
      return modal1;
    }
  }
  testerCheck (record ) {
    
    let testCheckPass = testrecordId => {
      this.props.dispatch({
        type: 'testrecord/testCheckPass',
        payload: testrecordId
      })
    }
  
    let testCheckFail = testrecordId => {
      this.props.dispatch({
        type: 'testrecord/testCheckFail',
        payload: testrecordId
      })
    }
    let modal1 = this.checkUserRole(3, '非测试人员，无权操作！');
    if (_.isUndefined(modal1)) {
      let modal2 = this.checkUserInProject(record);
      if (_.isUndefined(modal2)) {
        return Modal.confirm({
          title:"测试审核",
          maskClosable:true,
          destroyOnClose:true,
          onOk:() => testCheckPass(record.activeTestRecordId),
          onCancel:() => testCheckFail(record.activeTestRecordId),
          okText:"通过",
          cancelText:"不通过",
          content:(<div>
            <p>项目版本：{`${record.projectName}-${record.versionName}`}</p>
            <p>1. 请查看开发是否自测通过</p>
            <p>2. 快速验证基本功能（15-30min内完成，若验证未通过，务必打回）</p>
          </div>)
        })
      } else {
        return modal2;
      }
    } else {
      return modal1;
    }
  }

  handleDelete = (record) => {
      if([3,4,5].indexOf(record.testStatus) > -1){
        return Modal.info({
          title: '权限管理',
          content: '已打回、已提测的提测单不能删除！',
          destroyOnClose: true
        });
      }else{
        this.props.dispatch({
          type: 'testrecord/delete',
          payload: record.activeTestRecordId
        })
      }
  }

  handleEdit (record) {
    let status = 0;
    let { currentUserOwnedProjectList } = this.props;
    currentUserOwnedProjectList.forEach(
      function(data){
        if(data.id===record.projectId){
          status += 1
        }
      }
    ) 
    if(status===0){
      return Modal.info({
        title: '权限管理',
        content: '非该项目开发人员无法编辑',
        destroyOnClose: true
      });
    }else{
      this.props.dispatch({
        type:'testrecord/showEditForm',
        payload: record
      })
    }
  }

  handleCheck( record ) {
    this.props.dispatch({
      type:'testrecord/gotoRecordDetailPage',
      payload: record
    })
  }
  
  remarksCancel = () =>{
    this.setState({
      visible:false
    })
  }

  getProjectList = (value)=>{
    let list = value.map((r)=>{
      return{
        text: r.name,
        value: r.name
      }
    })

    return list
  }
  

  render() {
    let { list, pagination, loading, selectedRows, projectList, testStatusList } = this.props;
    let data = { list, pagination };
    let mapTestStatusCell = this.mapTestStatusCell;
    const projectArr = this.getProjectList(this.props.projectList)
    let { sortedInfo, filteredInfo } = this.state;
    filteredInfo = filteredInfo || {};
    sortedInfo = sortedInfo || {};
    const columns = [
      {
        title: '提测项目', 
        dataIndex: 'projectName', 
        key:'projectName',
        filters: projectArr,
        filteredValue: filteredInfo.projectName || null,
        onFilter: (value, record) => record.projectName.indexOf(value) === 0, 
      },
      { title: '提测版本', dataIndex: 'versionName' },
      {
        title: '提测次数',
        dataIndex: 'recordCount', 
        key:'recordCount',
        align: 'center',
        sorter: (a, b) => a.age - b.age,
        sortOrder: sortedInfo.columnKey === 'recordCount' && sortedInfo.order,
        render: val => `${val} 次`, needTotal: true
      },
      {
        title: '提测时间', 
        dataIndex: 'testCreateTime', 
        key:'testCreateTime',
        sorter: (a,b) =>a.testCreateTime > b.testCreateTime?1:-1, 
        sortOrder: sortedInfo.columnKey === 'testCreateTime' && sortedInfo.order,
        align: 'center',
        render: val => <span>{val && val !== '0000-00-00' ? moment(val).format('YYYY-MM-DD \n HH:mm:ss') : '--'}</span>,
      },
      {
        title: '预期提测时间', 
        dataIndex: 'expectTestTime', 
        align: 'center', 
        key:'expectTestTime',
        sorter: (a,b) =>a.expectTestTime > b.expectTestTime?1:-1,
        sortOrder: sortedInfo.columnKey === 'expectTestTime' && sortedInfo.order,
        render: val => <span>{moment(val).format('YYYY-MM-DD')}</span>,
      },
      {
        title: '状态', 
        dataIndex: 'testStatus', 
        key:'testStatus',
        filters: testStatusList,
        filteredValue: filteredInfo.testStatus || null,
        onFilter: (value, record) => record.testStatus==parseInt(value), 
        render(val) {
          return mapTestStatusCell(val);
        },
      },
      {
        title: '操作',
        align: 'center',
        render: (text, record) => {
          let testStatus = record.testStatus;
          if(testStatus === 0){
            return '--';
          }
            return <Fragment>
              <Icon style={{cursor:'pointer'}} type="eye" theme="twoTone" onClick={this.handleCheck.bind(this, record) } />
              <Divider type="vertical" />
              <Icon style={{cursor:'pointer'}} type="edit" theme="twoTone" onClick={this.handleEdit.bind(this, record)} />
              {/* <Divider type="vertical" />
              <Popconfirm title={`确定删除项目版本"${record.projectName}-${record.versionName}"的提测记录ID-${record.activeTestRecordId}吗?`} onConfirm={() => this.handleDelete(record)}>
                        <Icon type="delete" theme="twoTone" />
              </Popconfirm> */}
            </Fragment>
        },
      },
      {
        title: '审核/下一步',
        align: 'center',
        render: (text, record) => {
          let testStatus = record.testStatus;
          if (testStatus === 1) {
            return (<div>
              <Button icon="form"  style={{backgroundColor: "#007747", color:'white'}} onClick={this.pmCheckPass.bind(this, record)} >通过</Button>
              <Divider type="vertical" />
              <Button icon="form"  style={{backgroundColor: "#FF8000", color:'white'}} onClick={this.pmCheckFail.bind(this, record)} >打回</Button>
            </div>                    
            );
          }else if (testStatus === 2) {
            return (<div>
              <Button icon="form"  style={{backgroundColor: "#1E90FF", color:'white'}} onClick={this.testerCheckPass.bind(this, record)} >通过</Button>
              <Divider type="vertical" />
              <Button icon="form"  style={{backgroundColor: "#FF8000", color:'white'}} onClick={this.testerCheckFail.bind(this, record)} >打回</Button>
            </div>
            );
          }else if(testStatus === 0||testStatus === 3||testStatus === 4){
            return (<Button icon="form" type="primary" onClick={this.handleGoToTest.bind(this, record)} >去提测</Button>);
          }else{
            return "--";
            // return (<Button icon="form"  onClick={this.handleGoToTest.bind(this, record)} >重新提测</Button>);
          }
        },
      },
      
    ];

    return (
      <PageHeaderLayout title="版本提测记录">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListOperator}>
              <Button icon="form" type="primary" onClick={this.handleGoToTest.bind(this, undefined)} >
                我要提测
              </Button>
              {(selectedRows.length > 0 &&
                <span>
                  <Button>导出</Button>
                </span>
              )}
            </div>
            <Table
              selectedRows={selectedRows}
              loading={loading}
              dataSource={list}
              columns={columns}
              // onSelectRow={this.handleSelectedRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
         <TestRecordForm 
          visible={this.props.formModalVisible}
          data = {this.props.activeRecord}
          /> 
        <RemarksForm
          visible = {this.state.visible}
          sign = {this.state.sign}
          record ={this.state.record}
          onCancel = {this.remarksCancel}
        />  
      </PageHeaderLayout>
    );
  }
}
